<?php

require_once('conf/DBConnection.php');
require_once('dao/DAO.php');

class CiudadesDAO extends DAO {

	function CiudadesDAO() {}


	function get($id){
		DBConnection::getInstance();
		$query = "SELECT *, C.id as idCiudad FROM ciudades as C INNER JOIN provincias as P ON C.idProvincia=P.id WHERE C.id = $id";
		$result = mysql_query($query);
		$results = $this->getFromResult($result);
		return $results[0];
	}

	function find($criteria){
		DBConnection::getInstance();
		$criteria->setOrderby("C.ciudad");
		$conditions = $this->getConditions($criteria);
		$query = "SELECT *, C.id as idCiudad  FROM ciudades as C INNER JOIN provincias as P ON C.idProvincia=P.id WHERE 1=1 $conditions";
		//echo $query;
		$result = mysql_query($query);
		return $this->getFromResult($result);
	}

	function deleteFisico($id){
		DBConnection::getInstance();
		$query = "DELETE FROM ciudades WHERE id = $id";
		$result = mysql_query($query);
		return parent::checkError($result);
	}

	function delete($id){
		DBConnection::getInstance();
		$query = "UPDATE ciudades SET borrado = '1' WHERE id = $id";
		$result = mysql_query($query);
		return parent::checkError($result);
	}

	function insert($vo) {
		DBConnection::getInstance();
		$query = "INSERT INTO ciudades(id, ciudad, idProvincia, borrado) VALUES
('".$vo->getId()."', '".$vo->getCiudad()."', '".$vo->getIdProvincia()."', '".$vo->getBorrado()."')";
		$result = mysql_query($query);
		return parent::checkError($result);
	}

	function update($vo) {
		DBConnection::getInstance();
		$query = "UPDATE ciudades SET ".
				"ciudad ='".$vo->getCiudad()."', ".
				"idProvincia ='".$vo->getIdProvincia()."' ".
				" WHERE id =".$vo->getId();
		$result = mysql_query($query);
		return parent::checkError($result);
	}

	function getConditions($criteria){
		if ($criteria->getCiudad() != null) {
			$conditions.= " AND ciudad= '".$criteria->getCiudad()."'";
		}
		if ($criteria->getIdProvincia() != null) {
			$conditions.= " AND idProvincia= '".$criteria->getIdProvincia()."'";
		}
		$conditions .= parent::getConditionsAbs($criteria,'C');
		return $conditions;
	}

}

